package com.example.demo.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;

@Configuration
public class SwaggerConfig {

    /**
     * 统一安全认证请求头名称
     */
    static final String SECURITY_SCHEME_NAME = "satoken";

    private License license() {
        return new License()
                .name("MIT")
                .url("https://opensource.org/licenses/MIT");
    }

    private Info info() {
        return new Info()
                .title("xx系统/服务")
                .description("A test project for Mr.Ya.")
                .version("v1.0.0")
                .license(license());
    }

    private ExternalDocumentation externalDocumentation() {
        return new ExternalDocumentation()
                .description("这是一个额外的描述。")
                .url("https://shijizhe.github.io/");
    }

    private Components authorizationHeader() {
        return new Components()
                .addSecuritySchemes(SECURITY_SCHEME_NAME, new SecurityScheme()
                        .type(SecurityScheme.Type.APIKEY)
                        .in(SecurityScheme.In.HEADER)
                        .name(SECURITY_SCHEME_NAME));
    }

    @Bean
    public OpenAPI springShopOpenAPI() {
        // 此处的端口号 (8081) 与 application.yml 中的 management.server.port 对应
        System.out.println("\r\nswagger ui 访问路径: http://localhost:8081/actuator/swagger-ui/index.html \r\n");
        return new OpenAPI()
                .info(info())
                .components(authorizationHeader())
                .addSecurityItem(new SecurityRequirement().addList(SECURITY_SCHEME_NAME))
                .externalDocs(externalDocumentation());
    }
}
